<html>
<head>
<script type="text/javascript" src="atmosphere.js"></script>

<script type="text/javascript">

var getUri = function(path){
	return document.location.toString() + path;
} 
var request = {
        "url": getUri("chat/connect"),
        "transport": "websocket",
        "fallbackTransport": "long-polling",
        "logLevel" : "debug",
        "onMessage": function (response) {
            console.log("on message")
            console.log("response: " + response.responseBody)
            var responseBody = JSON.parse(response.responseBody)
            var ul = document.getElementById('messages');
            var li = document.createElement("li");
            li.innerHTML = responseBody.author+" : "+responseBody.text;
            ul.appendChild(li);
        }
    };

atmosphere.subscribe(request);

var sendMessage = function(author, text){
	var input = {"text":text, "author":author}
	
	var xhr = new XMLHttpRequest();
    xhr.open("POST", getUri("chat/sendMessage"), true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("accept", "application/json");

    xhr.send(JSON.stringify(input));
}

</script>
</head>

<body>
<ul id="messages">

</ul>

<form>
	<input type="text" id="author" value="John Doe"/>
	<input type="text" id="text" value="Hello"/>
	<button onclick="sendMessage(document.getElementById('author').value, document.getElementById('text').value);document.getElementById('text').value=null;return false;">Send</button>
</form>

</body>
</html>
